<script lang="ts" setup name="stockRealSheetEdit">
import ProTable from "@/components/ProTable/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
// import { MoreFilled } from "@element-plus/icons-vue";
import SelectTreeTable from "@/components/SelectTreeData/index.vue";
import PlanDialog from "@/views/inventory/stock/realsheet/components/PlanDialog.vue";
import type { FormInstance } from "element-plus";

import {
  checkStockRealSheet,
  createStockRealSheet,
  editStockRealSheet,
  getInventoryGoodsList,
  getStockPlanList,
  getStockRealSheetDetail,
  getStorehouseList,
  getWaresCategoryList
} from "@/api/modules/inventory";

const router = useRouter();
const route = useRoute();

/* 仓库start;*/
const storeList = ref<any[]>([]);
const onShowStore = async () => {
  const res = await getStorehouseList();
  storeList.value = res.data.list;
  storeList.value.forEach(v => {
    if (v.isDefault) {
      stockRealSheetForm.value.houseId = v.id;
    }
  });
};
const onselectChange = () => {
  // 防止编辑时选择仓库数据不会发生改变
  stockRealSheetForm.value.inventorydetailList = [];
};

const ruleFormRef = ref<FormInstance>();
const stockRealSheetForm = ref({
  orderId: 0,
  // corpId: 0,
  // storeId: 0,
  orderNo: "",
  range: 1,
  planOrderId: null,
  planOrderNo: null,
  checkerId: 0,
  // checkFlag: false,
  checkTime: null,
  createTime: "",
  houseId: 0,
  dateType: 0,
  // updateTime: null,
  remark: "",
  sysUserId: 0,
  dateType: 0,
  inventorydetailList: []
});
const houseIdD = ref(null); // 如果是编辑复原仓库是复原数据
const list = ref([]);
watch(
  () => stockRealSheetForm.value.houseId,
  () => {
    if (houseIdD.value === stockRealSheetForm.value.houseId && route.query.id) {
      stockRealSheetForm.value.inventorydetailList = list.value;
    }
  }
);

// 判断数据回来是否是可查看还是可编辑，查看禁用不能操作
const documentStatus: string = ref("add");
onMounted(async () => {
  onShowStore();
  if (route.query?.id) {
    const { data } = await getStockRealSheetDetail({ id: route.query.id });
    stockRealSheetForm.value = JSON.parse(JSON.stringify(data));
    list.value = data.inventorydetailList;
    houseIdD.value = data.houseId;
    console.log(data);

    // stockRealSheetForm.value = data;
    if (data.checkFlag) {
      documentStatus.value = "audited";
    } else {
      documentStatus.value = "edit";
    }
  } else {
    documentStatus.value = "add";
  }
});

const proTable = ref();
// 外层表格的列的每一项
const columns: ColumnProps<Inventory.ResPurchaseList>[] = [
  { type: "index", label: "序号", width: 60 },
  { prop: "operate", label: "操作", width: 100 },
  { prop: "barcode", label: "编码", minWidth: 220 },
  { prop: "name", label: "名称", minWidth: 140 },
  { prop: "realQuantity", label: "盘点数量", minWidth: 140 },
  { prop: "planQuantity", label: "账面数量", minWidth: 120 },
  { prop: "costPrice", label: "成本价", minWidth: 120 },
  { prop: "costAmount", label: "库存金额", minWidth: 120 },
  { prop: "profitLossQuantity", label: "盈亏数量", minWidth: 100 },
  { prop: "profitLossAmount", label: "盈亏金额", minWidth: 100 },
  { prop: "productName", label: "分类", minWidth: 100 },
  { prop: "unitName", label: "单位", minWidth: 120 }
];

// // 打开库存原料弹出层列表
const selectTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null);
const openSelectTreeTable = (title: string, searchVal: string | number) => {
  if (!stockRealSheetForm.value.houseId) return ElMessage.error("请先选择仓库");
  const params = {
    title,
    isView: false,
    searchVal,
    index: 0,
    mate: "productsId", // 勾选中数据字段
    // 底部选中的数据显示在底部
    selTags: stockRealSheetForm.value?.inventorydetailList
      .filter(age => age.goodsId !== 0)
      .map(i => {
        i.name = i.name;
        i.id = i.productsId;
        return i;
      }),
    columns: [
      { type: "selection", width: 80 },
      { prop: "barcode", label: "编码", align: "left", width: 200 },
      { prop: "name", label: "原料名称", align: "left", minWidth: 220 },
      { prop: "productName", label: "规格", align: "left", minWidth: 100 },
      { prop: "unitName", label: "单位", align: "left", minWidth: 160 },
      // { prop: "posPrice", label: "原料价格", minWidth: 120 }
      { prop: "purPrice", label: "采购价格", minWidth: 120 }
    ],
    apiParams: { houseId: stockRealSheetForm.value.houseId, planOrderId: stockRealSheetForm.value.planOrderId },
    idName: "goodsCategoryId",
    // 发请求
    treeApi: getWaresCategoryList,
    api: getInventoryGoodsList
  };
  selectTreeTableRef.value?.acceptParams(params);
};
// // 选中库存原料
const handleSelectedTreeList = (val: any) => {
  if (val.list.length > 0) {
    let list = val.list.map((im: any) => {
      return {
        name: im.name,
        id: im.id,
        // storeId: im.storeId,
        productsId: im.productsId,
        productName: im.productName,
        goodsId: im.id,
        planQuantity: im.planQuantity,
        price: im.costPrice,
        barcode: im.barcode,
        categoryName: im.categoryName,
        realQuantity: 0,
        costPrice: im.costPrice,
        costAmount: im.costAmount,
        unitName: im.unitName, // 单位
        profitLossQuantity: "",
        profitLossAmount: ""
      };
    });
    list.forEach(v => {
      if (!stockRealSheetForm.value.inventorydetailList.some(i => i.productsId === v.productsId)) {
        stockRealSheetForm.value.inventorydetailList.push(v);
      }
    });
  }
};

// 选择盘点计划单审核 --start--
const dialogVisible = ref(false);
const planList = ref<any>([]);
const searchVal = ref("");
const onSelectPlan = () => {
  dialogVisible.value = true;
};
// 监听弹出层
watch(
  () => dialogVisible.value,
  async val => {
    if (val) {
      if (!stockRealSheetForm.value.houseId) {
        ElMessage.error("请先选择仓库");
        dialogVisible.value = false;
      } else {
        const { data } = await getStockPlanList({
          orderType: 1,
          pageNum: 1,
          pageSize: 9999,
          // status: 1,
          isDetail: 1,
          houseId: stockRealSheetForm.value.houseId,
          orderNo: searchVal.value
        });
        planList.value = JSON.parse(JSON.stringify(data.list));
        // console.log(planList.value);
      }
    } else {
      searchVal.value = "";
    }
  }
);
// 监听搜索数据
watch(
  () => searchVal.value,
  async () => {
    if (!dialogVisible.value) return;
    const { data } = await getStockPlanList({ orderType: 1, pageNum: 1, pageSize: 9999, isDetail: 1, orderNo: searchVal.value });
    planList.value = JSON.parse(JSON.stringify(data.list));
    // console.log(planList.value);
  }
);
// 监听盘点范围
watch(
  () => stockRealSheetForm.value.range,
  val => {
    if (val === 1) {
      stockRealSheetForm.value = {
        orderId: 0,
        // corpId: 0,
        planOrderId: null,
        orderNo: "",
        range: 1,
        checkerId: 0,
        // checkFlag: false,
        checkTime: null,
        createTime: "",
        houseId: 0,
        dateType: 0,
        // updateTime: null,
        remark: "",
        sysUserId: 0,
        dateType: 0,
        planOrderId: null,
        planOrderNo: null,
        inventorydetailList: []
      };
    }
  }
);

// 选中数据
const onSelectPlanList = e => {
  Object.keys(stockRealSheetForm.value).forEach(key => {
    if (e.hasOwnProperty(key)) {
      stockRealSheetForm.value[key] = e[key];
    }
  });
  stockRealSheetForm.value.planOrderId = e.orderId;
  stockRealSheetForm.value.planOrderNo = e.orderNo;
  stockRealSheetForm.value.orderId = 0;
  stockRealSheetForm.value.orderNo = "";
  stockRealSheetForm.value.inventorydetailList = e.inventoryplandetailList;

  // console.log(stockRealSheetForm.value);
};
// 盘点计划数据 --end--

// 保存数据
const isPass = ref(false);
const onSubmit = async () => {
  if (stockRealSheetForm.value.inventorydetailList.length < 1) return ElMessage.error("原料明细不能为空");

  // 提示用户是否有0的数据 start
  if (stockRealSheetForm.value.inventorydetailList.some(e => e.realQuantity === 0)) {
    await ElMessageBox.confirm("原料是否有盘点数量为0", "温馨提示", {
      confirmButtonText: "是",
      cancelButtonText: "否",
      type: "warning"
    })
      .then(() => {
        isPass.value = true;
      })
      .catch(() => {
        isPass.value = false;
      });
  } else {
    isPass.value = true;
  }
  if (!isPass.value) return;
  // 提示用户是否有0的数据 end
  if (!route.query?.id) {
    await createStockRealSheet(stockRealSheetForm.value);
    router.push({
      path: "/stock/stockRealSheetList",
      query: {
        upList: true
      }
    });
  } else {
    await editStockRealSheet(stockRealSheetForm.value);
    router.push({
      path: "/stock/stockRealSheetList",
      query: {
        upList: true
      }
    });
  }
};

// 保存并审核
const onCheckSubmit = async () => {
  if (stockRealSheetForm.value.inventorydetailList.length < 1) return ElMessage.error("原料明细不能为空");

  // 提示用户是否有0的数据 start
  if (stockRealSheetForm.value.inventorydetailList.some(e => e.realQuantity === 0)) {
    await ElMessageBox.confirm("原料是否有盘点数量为0", "温馨提示", {
      confirmButtonText: "是",
      cancelButtonText: "否",
      type: "warning"
    })
      .then(() => {
        isPass.value = true;
      })
      .catch(() => {
        isPass.value = false;
      });
  } else {
    isPass.value = true;
  }
  if (!isPass.value) return;
  // // 提示用户是否有0的数据 end

  await checkStockRealSheet({ ...stockRealSheetForm.value, checkFlag: true });
  router.push({
    path: "/stock/stockRealSheetList",
    query: {
      upList: true
    }
  });
};

const delSpecRow = (index: number) => {
  if (stockRealSheetForm.value.inventorydetailList.length <= 1) return ElMessage.error("原料不能少于一条数据");
  stockRealSheetForm.value.inventorydetailList.splice(index, 1);
};
</script>

<template>
  <div class="table-box card">
    <div class="ed-head">
      <span class="title">{{ documentStatus === "edit" ? "修改" : documentStatus === "add" ? "新增" : "" }}盘点单</span>
      <el-icon class="pointer" @click="router.go(-1)"><CloseBold /></el-icon>
    </div>
    <el-form :model="stockRealSheetForm" label-width="120px" :rules="planRules" ref="ruleFormRef" :inline="true">
      <el-form-item label="单据号" prop="orderNo">
        <el-input class="width160" v-model="stockRealSheetForm.orderNo" disabled placeholder="系统自动生成" />
      </el-form-item>

      <el-form-item label="仓库" prop="houseId">
        <el-select
          class="width150"
          :disabled="documentStatus === 'audited'"
          v-model="stockRealSheetForm.houseId"
          @change="onselectChange"
          placeholder="请选择仓库"
        >
          <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="盘点范围" prop="range" v-if="documentStatus === 'add'">
        <el-select class="width150" v-model="stockRealSheetForm.range" :disabled="documentStatus === 'audited'">
          <el-option :value="1" label="实时盘点" />
          <el-option :value="2" label="计划盘点" />
        </el-select>
      </el-form-item>
      <!-- 选择单据 -->
      <el-form-item
        @click="onSelectPlan"
        label="盘点计划"
        prop="remark"
        v-if="documentStatus === 'add' && stockRealSheetForm.range === 2"
      >
        <el-input disabled v-model="stockRealSheetForm.planOrderNo" style="max-width: 600px">
          <template #append>
            <span style="cursor: pointer">选择单据</span>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="盘点计划单号" prop="planOrderNo" v-if="documentStatus !== 'add' && stockRealSheetForm.planOrderNo">
        <el-input class="width200" v-model="stockRealSheetForm.planOrderNo" placeholder="请填写" :rows="1" disabled />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input class="width150" v-model="stockRealSheetForm.remark" placeholder="请填写" :rows="1" type="textarea" />
      </el-form-item>
    </el-form>
    <!-- tool-button:自定头部右侧的按钮 -->
    <ProTable
      ref="proTable"
      row-key="id"
      :columns="columns"
      :data="stockRealSheetForm.inventorydetailList"
      :pagination="false"
      :is-card="false"
      :tool-button="documentStatus !== 'audited'"
    >
      <template #tableHeader>
        <el-button v-if="documentStatus !== 'audited'" type="primary" @click="openSelectTreeTable('选择原料')">
          添加原料明细
        </el-button>
      </template>
      <template #toolButton>
        <!-- 待审核才能确认收货 -->
        <el-button v-if="documentStatus !== 'audited'" type="primary" @click="onCheckSubmit"> 保存并审核 </el-button>
        <el-button v-if="documentStatus !== 'audited'" @click="onSubmit" type="primary"> 保存 </el-button>
        <el-button @click="router.go(-1)"> 返回 </el-button>
      </template>

      <template #realQuantity="{ row }">
        <el-input-number
          :controls="false"
          :disabled="documentStatus === 'audited'"
          v-model="row.realQuantity"
          :min="0"
          class="w100"
        >
        </el-input-number>
      </template>

      <template #operate="scope">
        <div class="flx-justify-between" v-if="documentStatus !== 'audited'">
          <el-icon size="18" color="#169D82" @click="openSelectTreeTable('选择原料')"><Plus /></el-icon>
          <el-icon @click="delSpecRow(scope.$index)" size="18" color="#f00"><Minus /></el-icon>
        </div>
      </template>
    </ProTable>

    <SelectTreeTable ref="selectTreeTableRef" @selected-list="handleSelectedTreeList"></SelectTreeTable>
    <plan-dialog
      :dialog-visible="dialogVisible"
      @change-visible="dialogVisible = $event"
      :plan-list="planList"
      @emit-search="searchVal = $event"
      @emit-select-list="onSelectPlanList"
    ></plan-dialog>
  </div>
</template>

<style lang="scss" scoped></style>
